package com.zhao.dota.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.mapper.UserHeroMapper;
import com.zhao.dota.model.Quotation;
import com.zhao.dota.model.UserGold;
import com.zhao.dota.model.UserHero;
import com.zhao.dota.service.UserGoldService;
import com.zhao.dota.service.UserHeroService;
import com.zhao.dota.vo.HeroVo;
import com.zhao.dota.vo.UserAchievementVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserHeroServiceImpl extends ServiceImpl<UserHeroMapper, UserHero> implements UserHeroService {

    @Resource
    private UserGoldService userGoldService;

    @Override
    public UserHero getHero(Quotation quotation) {
        UserHero userHero = new UserHero();
        userHero.setUserId(quotation.getUserId());
        userHero.setHeroId(quotation.getHeroId());
        userHero.setLeagueId(quotation.getLeagueId());
        userHero.setRoundId(quotation.getRoundId());
        save(userHero);
        return userHero;
    }

    @Override
    public List<UserAchievementVo> achievements(Integer leagueId) {
        List<UserAchievementVo> userAchievementVos = userGoldService.userGold(leagueId);
        Map<Integer, List<HeroVo>> userHeroes = userAchievementVos.parallelStream()
                .flatMap(u -> baseMapper.userHeroes(leagueId, u.getId()).stream())
                .collect(Collectors.groupingByConcurrent(HeroVo::getUserId));
        for (UserAchievementVo userAchievementVo : userAchievementVos) {
            userAchievementVo.setHeroes(userHeroes.getOrDefault(userAchievementVo.getId(), Collections.emptyList()));
            userAchievementVo.getHeroes().forEach(HeroVo::setAvatar);
        }
        return userAchievementVos;
    }

    @Override
    @Transactional
    public boolean remove(Integer leagueId, Integer userId, Integer heroId) {
        LambdaQueryWrapper<UserHero> query = Wrappers.lambdaQuery(UserHero.class)
                .eq(UserHero::getLeagueId, leagueId)
                .eq(UserHero::getHeroId, heroId)
                .eq(UserHero::getUserId, userId)
                .eq(UserHero::getLost, false);
        UserHero one = getOne(query);
        if (one == null) {
            return false;
        }
        one.setLost(true);
        updateById(one);
        UserGold gold = userGoldService.getByLeagueIdUserId(leagueId, userId);
        gold.setGold(gold.getGold() + 1);
        userGoldService.updateById(gold);
        return true;
    }

}
